package com.darren.euc.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.darren.euc.util.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.darren.euc.entity.AppSession;
import com.darren.euc.entity.City;
import com.darren.euc.entity.LoginValidate;
import com.darren.euc.entity.ProductType;
import com.darren.euc.entity.Province;
import com.darren.euc.entity.ResponseJSON;
import com.darren.euc.entity.SourceOfChannel;
import com.darren.euc.entity.Space;
import com.darren.euc.entity.SpaceStatus;
import com.darren.euc.service.LoginValidateService;
import com.darren.euc.service.ProductTypeService;
import com.darren.euc.service.SourceOfChannelService;
import com.darren.euc.service.SpaceService;
import com.darren.euc.service.SystemService;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/system")
public class SystemAction {
	
	private static final Logger log = Logger.getLogger(SystemAction.class);
	
	private static final SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyyMMddHHmmssSSS");

	@Autowired
    private LoginValidateService loginValidateService;
	
	@Autowired
    private SystemService systemService;
	
	@Autowired
    private SourceOfChannelService sourceOfChannelService;
	
	@Autowired
    private ProductTypeService productTypeService;
	
	@Autowired
    private SpaceService spaceService;

	@ResponseBody
	@RequestMapping(value = "alive", method = RequestMethod.GET)
	public ResponseJSON healthCheck() {
		return new ResponseJSON();
	}

	@ResponseBody
    @RequestMapping(value = "/refreshToken",method = RequestMethod.POST)
    public ResponseJSON refreshToken(@RequestBody JSONObject requestJson,HttpServletRequest request,HttpServletResponse response) {
		ResponseJSON responseJson = new ResponseJSON();
		JSONObject jsonData = new JSONObject();
		String accessToken = requestJson.getString("accessToken");
		String refreshToken = requestJson.getString("refreshToken");
		log.info(String.format("accessToken:%s;refreshToken:%s", accessToken,refreshToken));
		if(JWTUtil.verifyRefreshJWT(refreshToken) == true){
			JSONObject playLoad = JWTUtil.getRefreshPayload(refreshToken);
			log.info(String.format("playLoad:%s", playLoad));
			Long exp = playLoad.getLong("exp");
			if(exp != null){//Token expiration validation
				java.util.Date myDate=new java.util.Date();					   
				if(exp < myDate.getTime()){
					responseJson.setStatus(-2);
					responseJson.setMessage("refreshToken 过期，请重新登陆。");
					return responseJson;
				}
			}
			if(loginValidateService == null){
				log.info("loginValidateService is null");
			}
			LoginValidate loginValidate = loginValidateService.findById(Integer.parseInt(playLoad.getString("id")));
			if(loginValidate == null){//Login invalid, please login again.
				responseJson.setStatus(-3);
				responseJson.setMessage("session失效，请重新登陆。");
				return responseJson;
			}
			
			AppSession appSession = null;
			try {
				appSession = loginValidate.getApplicationSession();
			} catch (Exception ex) {
				log.error(ex.getMessage(),ex);
			}
			if(appSession == null){
				responseJson.setStatus(-4);
				responseJson.setMessage("session失效，请重新登陆。");
				return responseJson;
			}
			
			if(!StringUtil.isEmptyOrWhitespace(accessToken)){
//				if(!accessToken.equals(appSession.getAttribute("accessToken"))){
//					responseJson.setStatus(-5);
//					responseJson.setMessage("未找到对应的accessToken，请重新登陆。");
//					return responseJson;
//				}
			}
			
			if(!refreshToken.equals(appSession.getAttribute("refreshToken"))){
				responseJson.setStatus(-6);
				responseJson.setMessage("refreshToken已废弃，请重新登陆。");
				return responseJson;
			}
			accessToken = JWTUtil.generateAccessJWT(loginValidate);
			refreshToken = JWTUtil.generateRefreshJWT(loginValidate);
			String expires_in = PropertyHelper.getAccessTokenExpire();
			jsonData.put("accessToken", accessToken);
			jsonData.put("refreshToken", refreshToken);
			jsonData.put("expiresIn", expires_in);			
			appSession.setAttribute("accessToken", accessToken);
			appSession.setAttribute("refreshToken", refreshToken);			
			try {
				loginValidate.setApplicationSession(appSession);
			} catch (IOException e) {
				log.error(e.getMessage(),e);
			}			
			response.setHeader("accessToken", accessToken);
			response.setHeader("refreshToken", refreshToken);
			loginValidateService.save(loginValidate);
			responseJson.setData(jsonData);			
		}else{
			responseJson.setStatus(-1);
			responseJson.setMessage("refreshToken 过期，请重新登陆。");
			return responseJson;
		}
        return responseJson;
    }
	
	@ResponseBody
	@RequestMapping("/upload")
	public JSONObject saveSpace(@RequestParam(value = "file", required = false) MultipartFile file,
			@RequestParam(value = "folderName", required = true) String folderName,
			@RequestParam(value = "fileType", required = false) String fileType,
			@RequestParam(value = "fileNameChange", required = false, defaultValue = "1") Integer fileNameChange,
			HttpServletRequest request,
			HttpServletResponse response){
		JSONObject responseJson = new JSONObject();
		String accessToken = request.getHeader("accessToken");
		System.out.println("=======================================================================================");
		System.out.println(accessToken);
		System.out.println("=======================================================================================");
		try {			
			Date currentTime = new Date();
			String saveFileName = FORMATTER.format(currentTime);
			String saveFileNameNew = FORMATTER.format(currentTime)+"1";
			String fileName = file.getOriginalFilename();
			saveFileName = saveFileName + fileName.substring(fileName.lastIndexOf("."));
			saveFileNameNew = saveFileNameNew + fileName.substring(fileName.lastIndexOf("."));
			if (fileNameChange == 0){
				String prefix = "anshu_IBC@release_";
				String tmp = fileName.split(" ")[1];
				saveFileNameNew = prefix+tmp;
			}
			String fileUrl  = request.getSession().getServletContext().getContextPath()+"/upload/"+ folderName + "/" + saveFileNameNew;
			String path = request.getSession().getServletContext().getRealPath("upload/"+folderName);			
			File targetFile = new File(path, saveFileName);
			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}
			file.transferTo(targetFile);
			File tempFile = new File(path, saveFileName);
			File saveFile = new File(path, saveFileNameNew);
			if("图片".equals(fileType)){//图片上传,宽度大于1000,等比例缩小
				PicUtil.resizeWidthFixed(tempFile, saveFile, 1000, 60f);
				tempFile.delete();
				System.out.println("文件类型:"+fileType);
			}else{
				FileChannel inputChannel = null;
				FileChannel outputChannel = null;
				try {
					inputChannel = new FileInputStream(tempFile).getChannel();
					outputChannel = new FileOutputStream(saveFile).getChannel();
					outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
					tempFile.delete();
				} finally {
					inputChannel.close();
					outputChannel.close();
				}
			}
			String port = StringUtil.convertNullToEmptyString(request.getServerPort());
			String basePath = request.getScheme() + "://" + request.getServerName() ;
			if(!"".equals(port)){//把相对路径处理成绝对路径
				basePath += ":" + port;
			}
			responseJson.put("status", "0");
			responseJson.put("message", "文件上传成功！");
			if ("图片".equals(fileType)){
				responseJson.put("fileUrl", GenegateDomainUtil.generateValidPicUrl(basePath+fileUrl));
			}else {
				responseJson.put("fileUrl", basePath+fileUrl);
			}
		} catch (Exception e) {
			responseJson.put("status", "-1");
			responseJson.put("message", "文件上传失败！");
			log.error(e.getMessage(),e);
		}
		return responseJson;
	}
	
	
	@ResponseBody
    @RequestMapping(value = "/province",method = RequestMethod.POST)
    public List<Province> getAllProvinces(HttpServletRequest request,HttpServletResponse response) {
    	List<Province> provinces = systemService.getAllProvinces();   	
        return provinces;
    }
	
	@ResponseBody
    @RequestMapping(value = "/city",method = RequestMethod.POST)
    public List<City> getAllCities(HttpServletRequest request,HttpServletResponse response) {
    	List<City> cities = systemService.getAllCity();   	
        return cities;
    }
	
	
	@ResponseBody
    @RequestMapping(value = "/sourceofchannel",method = RequestMethod.POST)
    public List<SourceOfChannel> getAllSourceOfChannel(HttpServletRequest request,HttpServletResponse response) {
    	List<SourceOfChannel> sourceOfChannels = sourceOfChannelService.getAll();  	
        return sourceOfChannels;
    }
	
	@ResponseBody
    @RequestMapping(value = "/producttype",method = RequestMethod.POST)
    public List<ProductType> getAllProductType(HttpServletRequest request,HttpServletResponse response) {
    	List<ProductType> productTypes = productTypeService.getAll();  	
        return productTypes;
    }
	
	@ResponseBody
    @RequestMapping(value = "/spacestatus",method = RequestMethod.POST)
    public List<SpaceStatus> getAllSpaceStatus(HttpServletRequest request,HttpServletResponse response) {
    	List<SpaceStatus> spaceStatuses = systemService.getAllSpaceStatus();
        return spaceStatuses;
    }
	
	@ResponseBody
    @RequestMapping(value = "/space",method = RequestMethod.POST)
    public List<Space> getAllSpace(HttpServletRequest request,HttpServletResponse response) {
    	List<Space> spaces = spaceService.getAll();
        return spaces;
    }
	
	@ResponseBody
    @RequestMapping(value = "/screen/token",method = RequestMethod.POST)
    public ResponseJSON getScreenToken(HttpServletRequest request,HttpServletResponse response) {
		ResponseJSON responseJson = new ResponseJSON();		
		String screenToken = systemService.getScreenToken();
		responseJson.setData(screenToken);		
        return responseJson;
    }
	
	
	@RequestMapping(value = "/electronicScreen")
    public String getAllFunctions(HttpServletRequest request,HttpServletResponse response) {

        return "electronicScreen";
    }

}